package com.last1mile.web.control;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.last1mile.commons.CurrencyEnum;
import com.last1mile.commons.ServeEnum;
import com.last1mile.model.Login;
import com.last1mile.model.Serve;
import com.last1mile.model.Trade;
import com.last1mile.pojo.MerServeDO;
import com.last1mile.pojo.UserDO;
import com.last1mile.service.ServeService;
import com.last1mile.service.TradeService;
import com.last1mile.service.UserService;
import com.last1mile.validator.ServeValidator;

@Controller
@RequestMapping("/s/*")
@SessionAttributes("currentLogin")
public class ServeController {

    @Autowired
    @Qualifier("serveValidator")
    ServeValidator serveValidator;

    @Autowired
    @Qualifier("serveServiceImpl")
    ServeService   serveService;

    @Autowired
    @Qualifier("userServiceImpl")
    UserService    userService;

    @Autowired
    @Qualifier("tradeServiceImpl")
    TradeService   tradeService;
    
    

    @RequestMapping(value = "/{serveId}", method = RequestMethod.GET)
    public String serve(@PathVariable Integer serveId,HttpServletRequest request, ModelMap model) {
        if (request.getSession().getAttribute("currentLogin") != null) {
                Login login = (Login) request.getSession().getAttribute("currentLogin");
                model.addAttribute("currentLogin", login);
        }
        
        MerServeDO serveDo = this.serveService.queryServeById(serveId);
        model.addAttribute("serve", serveDo);

        UserDO merUser = this.userService.queryUserById(serveDo.getMerId());
        model.addAttribute("merUser", merUser);
        return "serve/PublicServe";
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/issue.html", method = RequestMethod.GET)
    public String issueServe(@ModelAttribute("serve") Serve serve, @ModelAttribute("currentLogin") Login login,
                             ModelMap model) {
        List<ServeEnum> serveList = (List<ServeEnum>) CollectionUtils.arrayToList(ServeEnum.values());
        List<CurrencyEnum> currencyList = (List<CurrencyEnum>) CollectionUtils.arrayToList(CurrencyEnum.values());
        model.addAttribute("serveList", serveList);
        model.addAttribute("currencyList", currencyList);
        return "serve/IssueServeForm";
    }

    
    @RequestMapping(value = "/issue.html", method = RequestMethod.POST)
    public String issueServeSubmit(@ModelAttribute("serve") Serve serve, BindingResult result, SessionStatus status) {
        serveValidator.validate(serve, result);
        if (result.hasErrors()) {
            return "serve/IssueServeForm";
        } else {
            this.serveService.createMerServe(serve);
            return "serve/IssueServeSuccess"; // FIXME 跳转要实现外部重定向以避免刷新页面的重复提交
        }
    }

    @RequestMapping(value = "/subscribe-{serveId}.html", method = RequestMethod.GET)
    public String subscribeServe(@PathVariable Integer serveId, @ModelAttribute("currentLogin") Login login,
                                 ModelMap model) {

        return "serve/SubscribeServeSuccess";
    }

    @RequestMapping(value = "/order-{serveId}.html", method = RequestMethod.GET)
    public String orderServe(@PathVariable Integer serveId, @ModelAttribute("currentLogin") Login login, ModelMap model) {
        MerServeDO serveDo = this.serveService.queryServeById(serveId);
        model.addAttribute("serve", serveDo);

        UserDO merUser = this.userService.queryUserById(serveDo.getMerId());
        model.addAttribute("merUser", merUser);
        return "serve/OrderServeForm";
    }

    @RequestMapping(value = "/order-{serveId}.html", method = RequestMethod.POST)
    public String orderServeSubmit(@PathVariable Integer serveId, @ModelAttribute("currentLogin") Login login,
                                   @ModelAttribute("trade") Trade trade, ModelMap model) {
        Integer subCount = this.serveService.countSubscribe(trade.getPerId(), trade.getMerId(), serveId);
        if ((subCount != null) && (subCount > 0)) {
            // 该买家已经关注过该服务，什么都不用做
        } else {
            // 默认下单过程缺省给买家创建该服务的关注
            this.serveService.createSubscribe(trade.getPerId(), trade.getMerId(), serveId);
        }

        Integer tradeId = this.tradeService.createTrade(trade);
        model.addAttribute("tradeId", tradeId);
        return "serve/OrderServeSuccess";// FIXME 跳转要实现外部重定向以避免刷新页面的重复提交
    }
    
    
}
